package com.nftturbocollection.facade;

import com.nftturboapi.collection.model.CollectionVO;
import com.nftturboapi.collection.request.CollectionPageQueryRequest;
import com.nftturboapi.collection.service.CollectionFacadeService;
import com.nftturbobase.response.PageResponse;
import com.nftturbobase.response.SingleResponse;
import com.nftturbocollection.domain.entity.Collection;
import com.nftturbocollection.domain.entity.convertor.CollectionConvertor;
import com.nftturbocollection.domain.request.CollectionInventoryRequest;
import com.nftturbocollection.domain.service.CollectionService;
import com.nftturbocollection.domain.service.impl.redis.CollectionInventoryRedisService;
import com.nftturborpc.facade.Facade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CollectionFacadeServiceImpl implements CollectionFacadeService {
    @Autowired
    private CollectionService collectionService;

    @Autowired
    private CollectionInventoryRedisService collectionInventoryRedisService;

    private static final Logger logger = LoggerFactory.getLogger(CollectionFacadeServiceImpl.class);

    @Override
    public PageResponse<CollectionVO> pageQuery(CollectionPageQueryRequest request) {
        PageResponse<Collection> collectionPage = collectionService.pageQueryByState(request.getKeyword(), request.getState(), request.getCurrentPage(), request.getPageSize());
        return PageResponse.of(CollectionConvertor.INSTANCE.mapToVo(collectionPage.getDatas()), collectionPage.getTotal(), collectionPage.getPageSize(), request.getCurrentPage());
    }

    @Override
    @Facade
    public SingleResponse<CollectionVO> queryById(Long collectionId) {
        // 查询藏品
        Collection collection = collectionService.queryById(collectionId);

        // 从redis中查询库存
        CollectionInventoryRequest request = new CollectionInventoryRequest();
        request.setCollectionId(collectionId.toString());
        Integer inventory = collectionInventoryRedisService.getInventory(request);

        if (inventory == null) {
            inventory = 0;
        }

        CollectionVO collectionVO = CollectionConvertor.INSTANCE.mapToVo(collection);
        collectionVO.setInventory(inventory.longValue());
        collectionVO.setState(collection.getState(), collection.getSaleTime(), inventory.longValue());
        return SingleResponse.of(collectionVO);
    }


}